package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.OrderReminder;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断地址是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断购物车是否为空
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(BaseContext.getCurrentId());
        if(shoppingCarts.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setNumber(BaseContext.getCurrentId()+String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setTablewareNumber(ordersSubmitDTO.getTablewareNumber());
        orders.setTablewareStatus(ordersSubmitDTO.getTablewareStatus());
        String address =addressBook.getProvinceName() +" "+ addressBook.getCityName() +" "+ addressBook.getDistrictName() +" "+ addressBook.getDetail();
        orders.setAddress(address);

        orderMapper.submitOrder(orders);
        //订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetails);

        //清空购物车
        shoppingCartMapper.cleanShoppingCart(BaseContext.getCurrentId());

        //返回vo
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 获取当前登录用户id，根据id获取用户信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        /*
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid

                if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        );*/

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        orderPaymentVO.setPackageStr(jsonObject.getString("package"));
        orderPaymentVO.setNonceStr(UUID.randomUUID().toString());

        paySuccess(ordersPaymentDTO.getOrderNumber());

        return orderPaymentVO;
    }

    /**

     * 支付成功，修改订单状态
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //来单提醒(基于webSocket)
        Map map = new HashMap();
        map.put("type", OrderReminder.ORDER_REMINDER);
        map.put("orderId",orders.getId());
        map.put("content","订单号:"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
        log.info("已提醒商家备餐");

        orderMapper.update(orders);
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrderPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orderVOS = (Page)orderMapper.historyOrderPageQuery(ordersPageQueryDTO);
        for (Orders orderVo : orderVOS) {
            List<OrderDetail> orderDetails = orderMapper.queryDetailByOrderId(orderVo.getId());
            orderVo.setOrderDetailList(orderDetails);
        }
        return new PageResult(orderVOS.getTotal(),orderVOS.getResult());
    }

    /**
     * 查询订单的详情
     * @param id
     * @return
     */
    @Override
    public Orders queryOrderDetail(long id) {
        Orders order = orderMapper.queryOrderDetail(id);
        order.setOrderDetailList(orderMapper.queryDetailByOrderId(id));
        return order;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(long id) {
        orderMapper.cancelOrder(id);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionOrder(long id) {
        List<ShoppingCart> shoppingCarts = orderDetailMapper.queryOrderDetail(id);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
        }
        for (ShoppingCart shoppingCart : shoppingCarts) {
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 管理端分页查询订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult OrderPageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> orderVOS = (Page)orderMapper.historyOrderPageQuery(ordersPageQueryDTO);
        //还需要到地址表中查询地址（根据地址id）
        for (OrderVO orderVO : orderVOS) {
            AddressBook addressBook = addressBookMapper.getById(orderVO.getAddressBookId());
            String address = addressBook.getProvinceName() +" "+ addressBook.getCityName() +" "+ addressBook.getDistrictName() +" "+ addressBook.getDetail();
            orderVO.setAddress(address);
        }
        //设置订单的菜品信息
        for (OrderVO orderVO : orderVOS) {
            List<ShoppingCart> shoppingCarts = orderDetailMapper.queryOrderDetail(orderVO.getId());
            String allDish = "";
            //shoppingCart表示每一个菜品或套餐
            for (ShoppingCart shoppingCart : shoppingCarts) {
                String dish = shoppingCart.getName() + "*" + shoppingCart.getNumber();
                allDish = allDish+dish+" ";
            }
            orderVO.setOrderDishes(allDish);
        }
        return new PageResult(orderVOS.getTotal(),orderVOS.getResult());
    }

    /**
     * 统计各个状态的订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO statistic() {
        List<Orders> orders = orderMapper.statistic();
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        for (Orders order : orders) {
            if(order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
                if(orderStatisticsVO.getToBeConfirmed()==null){
                    orderStatisticsVO.setToBeConfirmed(1);
                }else {
                    orderStatisticsVO.setToBeConfirmed(1+orderStatisticsVO.getToBeConfirmed());
                }
            }
            if(order.getStatus().equals(Orders.CONFIRMED)) {
                if(orderStatisticsVO.getConfirmed()==null){
                    orderStatisticsVO.setConfirmed(1);
                }else {
                    orderStatisticsVO.setConfirmed(1+orderStatisticsVO.getConfirmed());
                }
            }
            if(order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
                if(orderStatisticsVO.getDeliveryInProgress()==null){
                    orderStatisticsVO.setDeliveryInProgress(1);
                }else {
                    orderStatisticsVO.setDeliveryInProgress(1+orderStatisticsVO.getDeliveryInProgress());
                }
            }
        }
        return orderStatisticsVO;
    }

    /**
     * 商户接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 商户拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        orderMapper.reject(ordersRejectionDTO);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {

        Orders orders = orderMapper.queryOrderDetail(ordersCancelDTO.getId());
        //待付款状态不需要退款
        if(orders.getPayStatus() == Orders.UN_PAID){
            orderMapper.adminCancelOrder1(ordersCancelDTO);
        }else {
            orderMapper.adminCancelOrder2(ordersCancelDTO);
        }
    }

    @Override
    public void delivery(long id) {
        orderMapper.delivery(id);
    }


    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(long id) {
        orderMapper.complete(id);
    }

    @Override
    public void remind(long id) {
        Orders orders = orderMapper.queryOrderDetail(id);
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap();
        map.put("type", OrderReminder.CUSTOMER_REMINDERS);
        map.put("orderId",id);
        map.put("content","订单号:"+orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }
}
